/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package de.adorsys.ohos.securestoragetest.slice;

import de.adorsys.ohos.securestoragelibrary.SecurePreferences;
import de.adorsys.ohos.securestoragelibrary.SecureStorageException;
import de.adorsys.ohos.securestoragetest.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.utils.TextAlignment;
import ohos.agp.window.dialog.ToastDialog;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.multimodalinput.event.KeyEvent;

/**
 * MainAbilitySlice
 *
 * @since 2021-05-19
 */
public class MainAbilitySlice extends AbilitySlice implements Component.ClickedListener, Component.KeyEventListener {
    private static final HiLogLabel LABEL = new HiLogLabel(HiLog.INFO, 0x000110, "KeyEventListener");

    private static final int TEXT_SIZE = 30;
    private static final int DURATION_TIME = 2000;
    private static final int TOAST_DIALOG_RADIUS = 3000;
    private static final int DIALOG_PADDING = 30;
    private static final int ALPHA = 80;
    private static final int CORNER_RADIUS = 20;
    private static final String FAILED = "FAILED";

    private Button storeButton;
    private Button getButton;
    private Button removeButton;

    // 输入框
    private TextField storeKey;
    private TextField storeValue;
    private TextField getDataKey;
    private TextField removeDataKey;

    // 提示栏
    private Text storeTextTips;
    private Text getTextTips;
    private Text removeTextTips;

    // 输入框的值
    private String strokeKeyText;
    private String storeValueText;
    private String getDataKeyText;
    private String removeDataKeyText;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        initButton();
    }

    private void initButton() {
        storeButton = (Button) findComponentById(ResourceTable.Id_store_button);
        getButton = (Button) findComponentById(ResourceTable.Id_get_button);
        removeButton = (Button) findComponentById(ResourceTable.Id_remove_button);

        storeKey = (TextField) findComponentById(ResourceTable.Id_store_data_key);
        storeValue = (TextField) findComponentById(ResourceTable.Id_store_data_value);
        getDataKey = (TextField) findComponentById(ResourceTable.Id_get_data_key);
        removeDataKey = (TextField) findComponentById(ResourceTable.Id_remove_data_key);

        storeTextTips = (Text) findComponentById(ResourceTable.Id_storeTextTips);
        getTextTips = (Text) findComponentById(ResourceTable.Id_getTextTips);
        removeTextTips = (Text) findComponentById(ResourceTable.Id_removeTextTips);

        storeButton.setClickedListener(this::onClick);
        getButton.setClickedListener(this::onClick);
        removeButton.setClickedListener(this::onClick);
        storeKey.setUserNextFocus(Component.FOCUS_NEXT, ResourceTable.Id_store_data_value);
        storeValue.setUserNextFocus(Component.FOCUS_NEXT, ResourceTable.Id_get_data_key);
        getDataKey.setUserNextFocus(Component.FOCUS_NEXT, ResourceTable.Id_remove_data_key);

        storeKey.setKeyEventListener(this::onKeyEvent);
        storeValue.setKeyEventListener(this::onKeyEvent);
        getDataKey.setKeyEventListener(this::onKeyEvent);
    }

    @Override
    public boolean onKeyEvent(Component component, KeyEvent keyEvent) {
        HiLog.info(LABEL,"按键事件触发");
        if (checkFocus(keyEvent, storeKey)) {
            return true;
        } else if (checkFocus(keyEvent, storeValue)) {
            return true;
        } else if (checkFocus(keyEvent, getDataKey)) {
            return true;
        }
        return false;
    }

    private boolean checkFocus(KeyEvent keyEvent,TextField textField) {
        if (textField.hasFocus()) {
            // 如果不增加该判断则会触发两次
            if (keyEvent.isKeyDown()) {
                if (keyEvent.getKeyCode() == keyEvent.KEY_ENTER) {
                    textField.findRequestNextFocus(Component.FOCUS_NEXT);
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            case ResourceTable.Id_store_button:
                store();
                break;
            case ResourceTable.Id_get_button:
                get();
                return;
            case ResourceTable.Id_remove_button:
                remove();
                return;
            default:
        }
    }

    // 保存
    private void store() {
        // 获取key和value
        strokeKeyText = storeKey.getText();
        storeValueText = storeValue.getText();

        // 判空
        if (strokeKeyText.isEmpty() || "".equals(strokeKeyText)
            || storeValueText.isEmpty() || "".equals(storeValueText)) {
            createDialog();
            return;
        }
        try {
            SecurePreferences.setValue(getApplicationContext(), strokeKeyText, storeValueText);
        } catch (SecureStorageException ex) {
            HiLog.error(LABEL, ex + "");
        }

        // 展示成功信息
        storeTextTips.setMultipleLine(true);
        storeTextTips.setText("Value: " + storeValueText + " successfully saved for key: " + strokeKeyText);

        // 显示存储key value提示
        storeTextTips.setVisibility(Text.VISIBLE);

        // 隐藏获key取提示
        getTextTips.setVisibility(Text.INVISIBLE);

        // 隐藏删除提示
        removeTextTips.setVisibility(Text.INVISIBLE);

        // 输入框置空
        storeKey.setText("");
        storeValue.setText("");
    }

    // 根据key获取
    private void get() {
        getDataKeyText = getDataKey.getText();

        if (getDataKeyText.isEmpty() || "".equals(getDataKeyText)) {
            createDialog();
            return;
        }
        String value = SecurePreferences.getStringValue(getApplicationContext(), getDataKeyText, FAILED);
        getTextTips.setMultipleLine(true);
        getTextTips.setText("Decrypted Data for key: " + getDataKeyText + " = " + value);
        getTextTips.setVisibility(Text.VISIBLE);
        removeTextTips.setVisibility(Text.INVISIBLE);
        storeTextTips.setVisibility(Text.INVISIBLE);

        getDataKey.setText("");
    }

    // 根据key删除
    private void remove() {
        removeDataKeyText = removeDataKey.getText();
        if (removeDataKeyText.isEmpty() || "".equals(removeDataKeyText)) {
            createDialog();
            return;
        }
        String value = SecurePreferences.getStringValue(getApplicationContext(), removeDataKeyText, FAILED);
        HiLog.info(LABEL, "removeValue " + value);
        removeTextTips.setMultipleLine(true);
        if (FAILED.equals(value)) {
            removeTextTips.setText("Value for key: " + removeDataKey.getText() + " not exist !");
        } else {
            SecurePreferences.removeValue(getApplicationContext(), removeDataKeyText);
            removeTextTips.setText("Value for key: " + removeDataKey.getText() + " successfully deleted");
        }
        removeTextTips.setVisibility(Text.VISIBLE);
        getTextTips.setVisibility(Text.INVISIBLE);
        storeTextTips.setVisibility(Text.INVISIBLE);

        // 输入框置空
        removeDataKey.setText("");
    }

    // 提示弹窗
    private void createDialog() {
        ShapeElement shapeElement = new ShapeElement();
        shapeElement.setRgbColor(RgbColor.fromArgbInt(Color.GRAY.getValue()));
        shapeElement.setAlpha(ALPHA);
        shapeElement.setCornerRadius(CORNER_RADIUS);

        Text dialog = new Text(getContext());
        dialog.setText("Fields cannot be empty");
        dialog.setTextColor(Color.BLACK);
        dialog.setBackground(shapeElement);

        dialog.setTextAlignment(TextAlignment.HORIZONTAL_CENTER);
        dialog.setTextSize(TEXT_SIZE, Text.TextSizeType.PX);
        dialog.setPadding(DIALOG_PADDING, DIALOG_PADDING, DIALOG_PADDING, DIALOG_PADDING);
        new ToastDialog(getContext())
            .setSize(ComponentContainer.LayoutConfig.MATCH_CONTENT,
                ComponentContainer.LayoutConfig.MATCH_CONTENT)
            .setComponent(dialog)
            .setDuration(DURATION_TIME)
            .setCornerRadius(TOAST_DIALOG_RADIUS)
            // Toast显示在界面底部
            .setAlignment(LayoutAlignment.BOTTOM)
            .show();
    }
}
